package com.example.demo.arithmetic.datastructure.linkedlist2;

public class Leetcode21 {

    public static void main(String[] args) {
        ListNode head1 = new ListNode(9, null);
        ListNode head2 = new ListNode(8, head1);
        ListNode head3 = new ListNode(3, head2);
        ListNode list1 = new ListNode(1, head3);

        ListNode head5 = new ListNode(4, null);
        ListNode list2 = new ListNode(2, head5);

        ListNode head = new Leetcode21().mergeTwoLists(list1, list2);
        while (head != null) {
            System.out.println(head.val);
            head = head.next;
        }
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode prehead = new ListNode(-1);

        ListNode prev = prehead;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                prev.next = l1;
                l1 = l1.next;
            } else {
                prev.next = l2;
                l2 = l2.next;
            }
            prev = prev.next;
        }

        // 合并后 l1 和 l2 最多只有一个还未被合并完，我们直接将链表末尾指向未合并完的链表即可
        prev.next = l1 == null ? l2 : l1;

        return prehead.next;

//        作者：力扣官方题解
//        链接：https://leetcode.cn/problems/merge-two-sorted-lists/solutions/226408/he-bing-liang-ge-you-xu-lian-biao-by-leetcode-solu/
//        来源：力扣（LeetCode）
//        著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
    }
}
